package com.atguigu.spzx.manager.service.impl;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.CircleCaptcha;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.atguigu.exception.LoginException;
import com.atguigu.spzx.manager.mapper.SysUserMapper;
import com.atguigu.spzx.manager.service.SysUserService;
import com.atguigu.spzx.model.pojo.system.SysUser;
import com.atguigu.spzx.model.request.system.LoginRequest;
import com.atguigu.spzx.model.request.system.QueryRequest;
import com.atguigu.spzx.model.vo.common.Result;
import com.atguigu.spzx.model.vo.system.LoginVo;
import com.atguigu.spzx.model.vo.system.ValidateCodeVo;
import com.atguigu.spzx.utils.DYLAssert;
import com.atguigu.spzx.utils.MD5Util;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Objects;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * @author admin
 * @description 针对表【sys_user(用户表)】的数据库操作Service实现
 * @createDate 2024-12-24 19:30:00
 */
@Service
@Transactional
public class SysUserServiceImpl extends ServiceImpl<SysUserMapper, SysUser>
        implements SysUserService {
    @Autowired
    private SysUserMapper sysUserMapper;

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    /*
     * @description: 登录
     **/
    @Override
    public Result<LoginVo> doLogin(LoginRequest loginRequest) throws LoginException {
        String userName = loginRequest.getUserName();
        String password = loginRequest.getPassword();
        String validateValue = loginRequest.getCaptcha();
        String codeKey = loginRequest.getCodeKey();
        //KEYPOINT 用户的数据也是在这一次查询中获取
        SysUser user = sysUserMapper.selectOne(new QueryWrapper<SysUser>().eq("username", userName));
        //验证码是否正确
//        if (StringUtils.isEmpty(validateValue) || !Objects.equals(redisTemplate.opsForValue().get(codeKey), validateValue)) {
//            throw new LoginException(ResultEnum.CAPTCHA_ERROR);
//        }
        DYLAssert.isTrue(StringUtils.isNotEmpty(validateValue) && Objects.equals(redisTemplate.opsForValue().get(codeKey), validateValue),"验证码错误");
        //检查账号密码是否匹配
        //TODO 2024/12/24 Assert抛出异常但是不能识别是那种异常
        DYLAssert.notNull(user, "用户名或密码错误");
//        if (user == null) {
//            throw new LoginException(ResultEnum.LOGIN_FAILED);
//        }
//        if (!(MD5Util.encode(password).equals(user.getPassword()))) {
//            throw new LoginException(ResultEnum.LOGIN_FAILED);
//        }
        DYLAssert.isTrue((MD5Util.encode(password).equals(user.getPassword())),"用户名或密码错误");
        // 生成token 保存到redis中, 设置过期时间
        String token = UUID.randomUUID().toString().replace("-", "");
        String jsonString = JSON.toJSONString(user, SerializerFeature.BrowserSecure);
        redisTemplate.opsForValue().set("user:login:" + token, jsonString,6, TimeUnit.HOURS);

        //返回结果
        LoginVo loginVo = new LoginVo();
        loginVo.setToken(token);
        loginVo.setRefresh_token("");
        return Result.ok(loginVo);
    }

    /*
     * @description: 获取当前用户info
     **/
    @Override
    public SysUser getUserInfo(String token) throws LoginException {
        //TODO 2024/12/25 设置redis中的过期时间
        String json = redisTemplate.opsForValue().get("user:login:" + token);
        SysUser user = com.alibaba.fastjson.JSON.parseObject(json, SysUser.class);
        System.out.println("从redis中查询用户信息。。。。");
//        if (user == null) {
//            System.out.println("redis中没有查询到用户信息。。。");
//            throw new LoginException(ResultEnum.USER_INFO_NULL);
//        }
        DYLAssert.notNull(user,"获取用户失败");

        user.setName("张三");
        user.setUsername("zs");
        user.setAvatar("https://ts4.cn.mm.bing.net/th?id=OIP-C.7KH4CcveY3sV0Bv_zPyJVgAAAA&w=257&h=243&c=8&rs=1&qlt=90&o=6&dpr=1.3&pid=3.1&rm=2");
        return user;
    }

    @Override
    public ValidateCodeVo generateValidateCode() {
        CircleCaptcha captcha = CaptchaUtil.createCircleCaptcha(150, 48, 4, 20);
        String key = UUID.randomUUID().toString().replace("-", "");
        //验证码的值
        String value = captcha.getCode();
        //验证码图片
        String imageBase64 = captcha.getImageBase64();
        //存入redis
        //TODO 2024/12/25 设置redis中的过期时间
        redisTemplate.opsForValue().set(key, value);
        //返回结果
        ValidateCodeVo validateCodeVo = new ValidateCodeVo();
        validateCodeVo.setCodeImage("data:image/png;base64," + imageBase64);
        validateCodeVo.setCodeKey(key);
        return validateCodeVo;
    }

    @Override
    public void doLogout(String token) {
        Boolean delete = redisTemplate.delete("user:login:" + token);
        System.out.println("退出登录: "+delete);
    }

    @Override
    public Page<SysUser> findUserByPage(Integer pageNum, Integer pageSize, QueryRequest queryRequest) {
        Page<SysUser> page = new Page<>(pageNum,pageSize);
//        QueryWrapper<SysUser> wrapper = new QueryWrapper<>();
//        if (queryRequest.getUsername() != null){
//            wrapper.like("username",queryRequest.getUsername());
//        }
//        if (queryRequest.getCreateTimeBegin() != null){
//            wrapper.ge("creatTime",queryRequest.getCreateTimeBegin());
//        }
//        if (queryRequest.getCreateTimeEnd() != null){
//            wrapper.le("creatTime",queryRequest.getCreateTimeEnd());
//        }
        return sysUserMapper.selectUserPage(page, queryRequest);
    }
}




